from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework.decorators import action
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView, GenericAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from goods.models import SKU
from users import contants
from users import serializers
from users.models import User
from rest_framework import status

class UserView(CreateAPIView):
    # 接受参数
    serializer_class = serializers.CreateUserSerializer
    # 教研参数

    # 保存用户数据

    # 加密

    # 序列化，返回数据
class UsernameCountView(APIView):
    """
    用户名数量
    """
    def get(self, request, username):
        """
        获取指定用户名数量
        """
        count = User.objects.filter(username=username).count()

        data = {
            'username': username,
            'count': count
        }

        return Response(data)


# url(r'^mobiles/(?P<mobile>1[3-9]\d{9})/count/$', views.MobileCountView.as_view()),
class MobileCountView(APIView):
    """
    手机号数量
    """
    def get(self, request, mobile):
        """
        获取指定手机号数量
        """
        count = User.objects.filter(mobile=mobile).count()

        data = {
            'mobile': mobile,
            'count': count
        }

        return Response(data)

#GET/user/
class UserDetailView(RetrieveAPIView):
    """
    获取当前信息
    进行展示

    token验证
    数据库中查询数据，进行序列化输出

    """
    serializer_class = serializers.UserDetailSerializer
    permission_classes = [IsAuthenticated]

    def get_object(self):

        # user 只要user经历过jwt和apiview，就会有request自动认证user，并且放在其中，apiview继承view，as——view中直接封装了self。request
        return self.request.user


class EmailView(UpdateAPIView):

    # def put(self):
    # 获取校验查询更新，序列化

    serializer_class = serializers.EmailSerializer
    permission_classes = [IsAuthenticated]


    def get_object(self):
        return self.request.user

class VerifyEmailView(APIView):
    """
    邮箱验证
    """
    def get(self, request):
        # 获取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message': '缺少token'}, status=status.HTTP_400_BAD_REQUEST)

        # 验证token
        user = User.check_verify_email_token(token)
        if user is None:
            return Response({'message': '链接信息无效'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            user.email_active = True
            user.save()
            return Response({'message': 'OK'})

class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    serializer_class = serializers.UserAddressSerializer
    permission_classes = [IsAuthenticated]


    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted = False)

    def list(self):

        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset,many = True)

        user = self.request.user

        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': contants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    def create(self, request, *args, **kwargs):
        count = self.get_queryset().count()
        # count = request.user.addresses.count()
        if count >= contants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({"message":"達到上限"},status=status.HTTP_400_BAD_REQUEST)

        return super().create(request,*args,**kwargs)



    def destroy(self, request, *args, **kwargs):

        address = self.get_object()

        address.is_deleted = True

        address.save()

        return Response({"message":"刪除成功"},status=status.HTTP_204_NO_CONTENT)

    @action(methods=['put'], detail=True)
    def status(self, request, pk=None, address_id=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True)
    def title(self, request, pk=None, address_id=None):

        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address,data=request.query_params)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


class UserBrowsingHistory(mixins.CreateModelMixin, GenericAPIView):
    serializers=serializers.AddUserrHistorySerializer
    permission_classes = [IsAuthenticated]

    def post(self,request):

        return self.create(request)

    def get(self, request):
        # user_id
        user_id = request.user.id

        # 查询redis  list
        redis_conn = get_redis_connection('history')
        sku_id_list = redis_conn.lrange('history_%s' % user_id, 0, constants.USER_BROWSE_HISTORY_MAX_LIMIT)

        # 数据库
        # sku_object_list = SKU.objects.filter(id__in=sku_id_list)

        skus = []
        for sku_id in sku_id_list:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)

        # 序列化 返回
        serializer = serializers.SKUSerializer(skus, many=True)
        return Response(serializer.data)

